package gestionsession;

import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import sql.GestionBdd;

public class FenListeSession extends javax.swing.JDialog {
    
    Statement stmt1 = null;
    Statement stmt2 = null;
    
    int numeroSession = 0; 
    String libelleSession = null;
    String niveauSession = null;
    String dateSession = null;
    
    ArrayList<Client> lesClients = new ArrayList<Client>();

    private static String FILE = null;
    
    private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
      Font.BOLD);
  private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
      Font.NORMAL, BaseColor.RED);
  private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
      Font.BOLD);
  private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
      Font.BOLD);
    
    public FenListeSession(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    public void init(int pNumeroSession){
        
        numeroSession = pNumeroSession;
        
        try {
            
            System.out.println(numeroSession);
            Statement stmt1 = GestionBdd.connexionBdd(GestionBdd.TYPE_MYSQL, "formarmor","localhost", "root","");
            String req = "Select * from session_form where numero = " + numeroSession;
            ResultSet rs = GestionBdd.envoiRequeteLMD(stmt1,req);
            
            DefaultTableModel dtm = new ModeleJTableSession(0, 0);

            String header[] = new String[] { "Matricule ","Nom"};
            dtm.setColumnIdentifiers(header);
            jTable1.setModel(dtm);
            jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
             
            while(rs.next()) 
            {
                libelleSession = rs.getString("libelleform");
                niveauSession = rs.getString("niveauform");
                dateSession = rs.getString("datedebut");
                
                jLabel1.setText("Session : " + rs.getString("libelleform"));
                jLabel2.setText("Niveau : " + rs.getString("niveauform"));
                jLabel3.setText("Date : " + rs.getString("datedebut"));
                this.setTitle("Liste d'inscrits Session " + rs.getString("libelleform"));
            }
            
            req = "Select * from client, inscription where inscription.num_session = " + numeroSession + " and inscription.matricule = client.matricule";
            rs = GestionBdd.envoiRequeteLMD(stmt1,req);
           
            while(rs.next()) {
                
                Client unClient = new Client();
                unClient.setDate(rs.getString("date_inscription"));
                unClient.setNom(rs.getString("nom"));
                unClient.setMatricule(rs.getString("client.matricule"));
                lesClients.add(unClient);
                
                dtm.addRow(new Object[] { 
                    rs.getString("client.matricule"),
                    rs.getString("nom"), 
                });
            }
            
            
        } catch (SQLException ex) {
            Logger.getLogger(FenSession.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public void generationPDF() throws DocumentException, IOException {
        
        
        
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
            document.open();
            ajoutTitre(document);
            ajoutTable(document);
            document.close();
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + FILE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void ajoutTitre(Document document) throws DocumentException
    {
        Paragraph preface = new Paragraph();
        preface.add(new Paragraph("Session " + libelleSession + " (" + niveauSession + ") du " + dateSession, catFont));
        document.add(preface);
    }
    
    public void ajoutTable(Document document) throws DocumentException
    {
        PdfPTable table = new PdfPTable(3);
        PdfPCell c1 = new PdfPCell(new Phrase("Matricule"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Nom"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Date d'inscription"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.setHeaderRows(1);
        
        for(Client unClient : lesClients)
        {
            table.addCell(unClient.getMatricule());
            table.addCell(unClient.getNom());
            table.addCell(unClient.getDate());
        }
        
        Paragraph tableau = new Paragraph();
        addEmptyLine(tableau, 3);
        tableau.add(table);
        document.add(tableau);
    }
    
    
    private static void addEmptyLine(Paragraph paragraph, int number) {
    for (int i = 0; i < number; i++) {
      paragraph.add(new Paragraph(" "));
    }
  }
    
    
    

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("lblLibelle");

        jLabel2.setText("lblNiveau");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel3.setText("lblDate");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText("Exporter en PDF");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addGap(8, 8, 8))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(255, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            try {
                if(lesClients.isEmpty())
                {
                    JOptionPane.showMessageDialog(this, "Session vide");
                }
                else
                {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setCurrentDirectory(new File("/home/me/desktop"));
                    int retrival = chooser.showSaveDialog(null);
                    if (retrival == JFileChooser.APPROVE_OPTION) {
                        try {
                            FileWriter fw = new FileWriter(chooser.getSelectedFile()+".pdf");
                            fw.flush();
                            fw.close();
                            FILE = chooser.getSelectedFile().getAbsolutePath();
                            FILE += ".pdf";
                            System.out.println(FILE);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    generationPDF();
                }
                
            } catch (IOException ex) {
                Logger.getLogger(FenListeSession.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (DocumentException ex) {
            Logger.getLogger(FenListeSession.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
